<template>
  <div class="identityInfo">
    <van-nav-bar
        :title="$t('identity_auth')"
        left-arrow
        @click-left="$router.go(-1)"
    />
    <!--     身份信息-->
    <div style="padding: 10px">
      <div class="content_list">
        <div class="content_item" v-if="resourcesShow['idcard'] === 1">
          <div>
            <img class="image" src="../../assets/icon_card_mumber.png">
            <span class="text">{{ $t('id_card') }}</span>
          </div>
          <input class="input" onkeyup="value=value.replace(/[^\d]/g,'')" v-model="idCard"
                 :placeholder="$t('hint_input_id_card')" maxlength="12"/>
        </div>
        <!--        姓名-->
        <div class="content_item " style="display: block" v-if="resourcesShow['name'] === 1">
          <div style="width: 100%;">
            <div>
              <img class="image" src="../../assets/icon_contacts_name.png">
              <span class="text">{{ $t('name') }}</span>
            </div>
            <input class="input" v-model="name" :placeholder="$t('hint_input_name')"/>
          </div>
          <div class="name_tips">{{ $t('hint_tips_name_empty') }}</div>
        </div>
        <!--      选择性别-->
        <div class="content_item" @click="sexShow = true" v-if="resourcesShow['gender'] === 1">
          <div>
            <img class="image" src="../../assets/icon_contacts_two.png">
            <span class="text">{{ $t('sex') }}</span>
          </div>
          <div class="select_right">
            <span v-if="gender" class="select_right_text">{{ gender }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_sex') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      选择生日-->
        <div class="content_item" @click="birthdayShow = true" v-if="resourcesShow['dateBirth'] === 1">
          <div>
            <img class="image" src="../../assets/icon_birthday.png">
            <span class="text">{{ $t('birthday') }}</span>
          </div>
          <div class="select_right">
            <span v-if="dateBirth" class="select_right_text">{{ dateBirth }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_birthday') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <van-action-sheet v-model:show="sexShow" :actions="sexActions" @select="onSexSelect"/>
        <van-action-sheet v-model:show="birthdayShow" :actions="birthdayActions">
          <van-datetime-picker
              @confirm="onBirthdaySelect"
              @cancel="onBirthdayCancel"
              v-model="currentDate"
              type="date"
              :min-date="minDate"
              :max-date="maxDate"
          />
        </van-action-sheet>
      </div>
      <!--    上传身份证-->
      <div class="update_idcard">
        <!--        正面-->
        <div class="update_item" v-if="resourcesShow['frontIdCardUrl'] === 1">
          <van-uploader v-if="confirmShow" accept=".jpg,.jpeg,.png,.JPG,.JPEG" name="cover" :before-read="beforeRead"
                        :after-read="updatePositive">
            <img v-show="idCardImg1" class="image" :src="idCardImg1">
            <img v-show="!idCardImg1" class="image" :src="require('../../assets/icon_front_card.png')">
          </van-uploader>
          <img v-else class="image" :src="idCardImg1">
          <div class="text">{{ $t('upload_front_card') }}</div>
        </div>
        <!--        反面-->
        <div class="update_item" v-if="resourcesShow['negativeIdCardUrl'] === 1">
          <van-uploader v-if="confirmShow" accept=".jpg,.jpeg,.png,.JPG,.JPEG" :before-read="beforeRead"
                        :after-read="updateReverseSide">
            <img v-show="idCardImg2" class="image" :src="idCardImg2">
            <img v-show="!idCardImg2" class="image" :src="require('../../assets/icon_front_card.png')">
          </van-uploader>
          <img v-else class="image" :src="idCardImg2">
          <div class="text">{{ $t('upload_reverse_card') }}</div>
        </div>
        <!--        手持-->
        <div class="update_item" v-if="resourcesShow['handIdCardUrl'] === 1">
          <van-uploader v-if="confirmShow" accept=".jpg,.jpeg,.png,.JPG,.JPEG" :before-read="beforeRead"
                        :after-read="updateHold">
            <img v-show="idCardImg3" class="image" :src="idCardImg3">
            <img v-show="!idCardImg3" class="image" :src="require('../../assets/icon_front_card.png')">
          </van-uploader>
          <img v-else class="image" :src="idCardImg3">
          <div class="text">{{ $t('upload_hold_card') }}</div>
        </div>
      </div>
      <div class="confirm" v-show="confirmShow">
        <button @click="confirm">{{ $t('finish') }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, toRefs, reactive, inject} from 'vue'
import {useRoute} from 'vue-router'
import {useI18n} from 'vue-i18n'
import {dateFormat, debounce, processNext, setResourcesShow, compressImage} from '@/utils/tool'
import {Dialog, Toast} from 'vant'
import {jumpOperatorAuth, uploadUserInfo, userInfoConfirm} from '@/api/home'
import {useStore} from "vuex";

export default {
  setup() {
    const {tm} = useI18n()
    const store = useStore()
    const currentDate = ref(new Date(1990, 0, 1))
    let userInfo = reactive({
      name: null,
      idCard: null,
      gender: null,
      dateBirth: null,
      positive: null,
      reverseSide: null,
      hold: null,
    })
    const confirmShow = ref(true)
    const resourcesShow = ref({})
    const routes = useRoute()
    const idCardImg1 = ref(null)
    const idCardImg2 = ref(null)
    const idCardImg3 = ref(null)
    let sexSheet = reactive({
      sexShow: false,
      sexActions: [{name: tm('male'), key: 1}, {name: tm('female'), key: 0}],
      onSexSelect: (value) => {
        userInfo.gender = value.name
        sexSheet.sexShow = false
      },
    })


    let birthdaySheet = reactive({
      minDate: new Date(1910, 0, 1),
      maxDate: new Date(),
      birthdayShow: false,
      birthdayActions: [],
      onBirthdaySelect: (value) => {
        const time = dateFormat(value, 'YYYY-mm-dd')
        userInfo.dateBirth = time
        birthdaySheet.birthdayShow = false
      },
      onBirthdayCancel() {
        birthdaySheet.birthdayShow = false
      }
    })
    const beforeRead = (file) => {
      return new Promise(async (resolve, reject) => {
        const fileType = ['image/jpeg', 'image/png', 'image/jpg']
        if (fileType.indexOf(file.type) === -1) {
          Toast('upload_image');
          reject()
        } else if (file.size < Math.pow(1024, 2)) {
          // 小于1m不压缩
          resolve(file)
        } else {
          // 压缩图片
          const caseFile = await compressImage(file)
          resolve(caseFile)
        }
      })
    }


    const undateLoad = async (file, type) => {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', type)
      const res = await uploadUserInfo(formData)
      if (res.code === 1 && res.data) {
        return res.data
      }
    }
    // 上传正面
    const updatePositive = async (file) => {
      const res = await undateLoad(file.file, 2)
      userInfo.positive = res
      idCardImg1.value = res
    }
    // 上传反面
    const updateReverseSide = async (file) => {
      const res = await undateLoad(file.file, 3)
      userInfo.reverseSide = res
      idCardImg2.value = res
    }
    // 上传手持
    const updateHold = async (file) => {
      const res = await undateLoad(file.file, 1)
      userInfo.hold = res
      idCardImg3.value = res
    }
    // 回显内容
    if (localStorage.getItem('userWriteInfo')) {
      const {
        handIdCardUrl,
        frontIdCardUrl,
        negativeIdCardUrl,
        idcard,
        name,
        dateBirth,
        gender
      } = JSON.parse(localStorage.getItem('userWriteInfo'))
      userInfo = {
        name: name,
        idCard: idcard,
        positive: frontIdCardUrl,
        reverseSide: negativeIdCardUrl,
        hold: handIdCardUrl,
        gender: gender === '1' ? tm('male') : gender === '0' ? tm('female') : null,
        dateBirth: dateBirth
      }
      const show = Object.values(userInfo).filter(item => item)
      confirmShow.value = show.length === 7 ? false : true
      idCardImg1.value = frontIdCardUrl
      idCardImg2.value = negativeIdCardUrl
      idCardImg3.value = handIdCardUrl
    }
    const verificationInfo = () => {
      let message = null
      const {name, idCard, gender, dateBirth, reverseSide, positive, hold} = userInfo
      // 校验身份证
      const rulesIdCard = () => {
        /**
         * 越南身份证规则
         * 长度：9位或12位
         * 格式校验
         * 第4位为性别表示，偶数为男，奇数为女
         * 第5和6位为出身年份，格式为yy
         * 必须开启了身份认证，性别和生日才认证
         * num 1 男 0 女
         */
        if (idCard.length === 12) {
          const cardGender = idCard.slice(3, 4)
          const cardBirth = idCard.slice(4, 6)
          const entryBirth = dateBirth.slice(2, 4)
          const cardGenderValue = parseInt(cardGender) % 2 === 0 ? tm('male') : tm('female')
          if (gender !== cardGenderValue) return true
          if (cardBirth !== entryBirth) return true
        } else if (idCard.length === 9 || idCard.length === 12) {
          return false
        } else {
          return true
        }
        return false
      }
      if (!idCard && resourcesShow.value['idcard'] === 1) return message = tm('hint_input_id_card')
      if (!name && resourcesShow.value['name'] === 1) return message = tm('hint_input_name')
      if (!gender && resourcesShow.value['gender'] === 1) return message = tm('hint_select_sex')
      if (!dateBirth && resourcesShow.value['dateBirth'] === 1) return message = tm('birthday')
      if (rulesIdCard()) return message = tm('hint_input_idcard_error')
      if (!positive && resourcesShow.value['frontIdCardUrl'] === 1) return message = tm('hint_upload_front_card')
      if (!reverseSide && resourcesShow.value['negativeIdCardUrl'] === 1) return message = tm('hint_upload_reverse_card')
      if (!hold && resourcesShow.value['handIdCardUrl'] === 1) return message = tm('hint_upload_hold_card')
      return message
    }
    const confirm = debounce(async () => {
      const message = verificationInfo()
      if (!message) {
        Dialog.confirm({
          title: tm('tip'),
          message: tm('confirm_identity'),
        }).then(async () => {
          const {name, idCard, gender, dateBirth} = userInfo
          const params = {
            name: name,
            idcard: idCard,
            gender: gender === tm('male') ? 1 : 0,
            dateBirth: dateBirth,
          }
          const res = await userInfoConfirm(params)
          if (res.code === 1) {
            Toast({
              message: tm('submit_success')
            })
            const userWriteInfo = JSON.parse(localStorage.getItem('userWriteInfo'))
            localStorage.setItem('userWriteInfo', JSON.stringify({...userWriteInfo, name: userInfo.name}))
            processNext('identityInfo', routes.query.backName)
          }
        }).catch(() => {
        })
      } else {
        Toast({
          message: message
        })
      }
    })
    // 流程显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(1)
      // 清除loading
      store.dispatch('changeLoading', false)
    }
    getResourcesShow()
    return {
      ...toRefs(sexSheet),
      ...toRefs(birthdaySheet),
      resourcesShow,
      ...toRefs(userInfo),
      currentDate,
      beforeRead,
      updateHold,
      updateReverseSide,
      updatePositive,
      confirm,
      confirmShow,
      idCardImg1,
      idCardImg2,
      idCardImg3,
    }
  },
}
</script>

<style scoped lang="less">
.identityInfo {
  background-color: #f2f3f5;
  overflow: auto;

  ::v-deep .van-nav-bar {
    background: linear-gradient(90deg, #FF5252, #FF8244) !important;
    z-index: 1999;
  }

  ::v-deep .van-nav-bar .van-icon {
    color: #333333 !important;
  }

  .content_list {
    .content_item {
      border-bottom: solid 1px #f2f3f5;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px 10px;

      .name_tips {
        font-size: 10px;
        margin-left: 35px;
        margin-bottom: 5px;
        color: #FF5252;
      }

      div {
        height: 100%;
        display: flex;
        align-items: center;

        .image {
          height: 25px;
          width: 25px;
          margin-right: 10px;
        }

        .text {
          font-size: 12px;
          font-weight: 600;
        }
      }

      .select_right_text {
        color: #9D9D9D;
        font-size: 12px;
        margin-right: 5px;
      }

      .select_right {
        margin-right: 5px;
        color: #333333;
        font-size: 12px;
        flex: 1;
        justify-content: flex-end;
      }

      .input {
        width: 100px;
        border: none;
        text-align: right;
        height: 25px;
        font-size: 14px;
        flex: 1;
      }
    }
  }

  .update_idcard {
    .update_item {
      margin-top: 10px;
      background-color: #ffffff;
      border-radius: 5px;
      text-align: center;
      padding: 5px;

      .image {
        height: 117.5px;
        width: 185px;

      }

      .text {
        color: #9D9D9D;
        font-size: 12px;
      }
    }
  }

  .confirm {
    margin-top: 20px;
    text-align: center;

    button {
      width: 300px;
      padding: 10px 0;
      color: #ffffff;
      border: none;
      font-size: 16px;
      background: linear-gradient(-45deg, #FF5252, #FF8C3C);
      box-shadow: 0px 4px 10px 0px rgba(255, 92, 78, 0.52);
      border-radius: 29px;
    }

  }
}
</style>
